#ifndef LAUNCHER_H
#define LAUNCHER_H

#include <head/g_pch_core.h>
#include "analyzer.h"

class Launcher : public QObject
{
    Q_OBJECT
public:
    Launcher(QObject *parent = nullptr):
        QObject(parent)
    {
        isAwake=false;
        isAnalyzing=false;
    }

    ~Launcher()
    {
        stopAnalyzer();
    }

    void start()
    {
        appendMessage(QString("%1 已启动，当前版本 %2").arg(SP_NAME).arg(SP_VER));
        startAnalyzer();
        awake();

        analyzeId=startTimer(AUTOSAVE_INTERVAL);
    }

    void timerEvent(QTimerEvent *event)
    {
        if(QTime::currentTime() >= QTime::fromString(CUTOFF_TIME,TIME_FORMAT))
        {
            qDebug() << "下班了，程序现在退出";
            QCoreApplication::quit();
        }

        if(event->timerId() == analyzeId)
            processAnalyze();
    }

    void processAnalyze()
    {
        if(isAnalyzing)
            return;

        auto offset=QDate::currentDate().dayOfYear();
        auto beginDate=QDate::currentDate().addDays(1 - offset).toString(DATE_FORMAT);

        analyze(beginDate);
    }

    void startAnalyzer()
    {
        analyzer=new Analyzer;
        connect(analyzer,&Analyzer::popMessage,this,&Launcher::appendMessage);
        connect(analyzer,&Analyzer::awake,this,&Launcher::onAwake);
        connect(analyzer,&Analyzer::analyzing,this,&Launcher::onAnalyzing);

        connect(this,&Launcher::awake,analyzer,&Analyzer::onAwake);
        connect(this,&Launcher::analyze,analyzer,&Analyzer::onAnalyze);
        connect(this,&Launcher::testDL,analyzer,&Analyzer::onTest_DL);
        connect(this,&Launcher::testEB,analyzer,&Analyzer::onTest_EB);
        connect(&analyzeThread,&QThread::finished,analyzer,&QObject::deleteLater);

        analyzer->moveToThread(&analyzeThread);
        analyzeThread.start();
    }

    void stopAnalyzer()
    {
        analyzeThread.quit();
        analyzeThread.wait();
    }

    void onAwake(bool flag)
    {
        isAwake = flag;
        if(isAwake)
            appendMessage("分析器已启动");
        else
            appendMessage("分析器启动失败");
    }

    void onAnalyzing(bool flag)
    {
        isAnalyzing = flag;
    }

    void appendMessage(const QString &message)
    {
        qDebug() << CurrentDateTime << message << Qt::endl;
    }

signals:
    void awake();
    void debug();
    void analyze(const QString &beginDate);
    void testDL(const QString &cDLCode);
    void testEB(const QString &tid);

private:
    bool isAwake;
    bool isAnalyzing;

    int analyzeId;
    Analyzer *analyzer;
    QThread analyzeThread;
};

#endif // LAUNCHER_H
